// pages/xingzuanBuy/xingzuanBuy.js
const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    number: '', // 买入数量
    sum: '', // 买入总价
    unitPrice: '', // 买入单价
    xjNumber: '' // 星钻数量
  },
  // 获取input中用户输入买入数量的值
  getNum(e) {
    this.setData({
      number: e.detail.value
    })
    var sum = 0,
      number = this.data.number,
      unitPrice = this.data.unitPrice
    sum = number * unitPrice
    this.setData({
      sum: sum.toFixed(2)
    })
  },
  // 点击买入星钻按钮提交相应数据
  Buy() {
    var sum = 1
    var number = this.data.number
    var unitPrice = this.data.unitPrice
    sum = (number * unitPrice).toFixed(2)
    this.setData({
      sum
    })
    wx.request({
      url: app.globalData.baseUrl + '/currency/buyCurrency',
      data: {
        xcxOpenId: app.globalData.xcxOpenId,
        num: number,
        total: sum
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      method: 'POST',
      success(res) {
        var currencyId = res.data.data
        wx.request({
          url: app.globalData.baseUrl + '/currency/pay/payment',
          data: {
            xcxOpenId: app.globalData.xcxOpenId,
            currencyId: currencyId,
            price: sum * 100
          },
          header: {
            'content-type': 'application/x-www-form-urlencoded' // 默认值
          },
          method: 'POST',
          success(data) {
            console.log(data)
            wx.requestPayment({
              timeStamp: data.data.data.timeStamp,
              nonceStr: data.data.data.nonceStr,
              package: data.data.data.package,
              signType: 'MD5',
              paySign: data.data.data.paySign,
              success(res) {
                wx.showToast({
                  title: '支付成功',
                  icon: 'none'
                })
                wx.navigateTo({
                  url: '/pages/xingzuan/xingzuan',
                })
              },
              fail(res) {}
            })
          }
        })
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this
    // 获取星钻买入单价
    wx.request({
      url: app.globalData.baseUrl + '/currency/getCurrencyPrice',
      data: {
        xcxOpenId: app.globalData.xcxOpenId,
        mark: 1 //1代表买入2代表卖出
      },
      success(res) {
        var data = res.data.data
        that.setData({
          unitPrice: data
        })
      }
    })
  }
})